package com.zyf.controller;


import com.zyf.common.result.Result;
import com.zyf.service.MsmService;
import com.zyf.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/** 发送短信服务 api
 * @author zyf
 * @date 2021年05月18日 15:04
 */
@Api("短信服务")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/send/{phone}")
    //@ApiImplicitParam(name = "phone",value = "电话")
    public Result sendCode(@PathVariable String phone){
        //从redis中获取验证码，如果获取到，返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            redisTemplate.delete(phone);
        }
        //如果从redis获取不到，生成验证码，通过整合短信服务进行发送，生成的验证码放在redis中，设置有效时间
        String NewCode = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.sendCode(phone,NewCode);
        if (isSend){
            redisTemplate.opsForValue().set(phone,NewCode,5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }
}
